package com.pauldada.sakurabbs.controllers;

import com.pauldada.sakurabbs.entities.UserAccount;
import com.pauldada.sakurabbs.file.FileService;
import com.pauldada.sakurabbs.file.UploadFileResponse;
import com.pauldada.sakurabbs.services.UserAccountService;
import com.pauldada.sakurabbs.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.security.Principal;
import java.util.List;

@Controller
@RequestMapping("userAccounts")
public class UserAccountController {

    @Autowired
    FileService fileService;

    @Value("${imageFilePath}")
    private String imageFilePath;

    @Autowired
    UserAccountService userAccountService;

    UserAccount userInformation;

    @GetMapping
    public String DisplayUserAccounts(Model model){
        List<UserAccount> userAccounts = userAccountService.getAll();
        model.addAttribute("userAccounts",userAccounts);
        return "userAccounts/list-userAccounts";
    }

    @GetMapping("/info")
    public String UserAccountInfo(Model model,Principal principal){
        if (principal==null){
            return "/login";
        }
        String name = principal.getName();
        UserAccount userAccount = userAccountService.findByUsername(name);
        long Id = userAccount.getUserId();
        userInformation = userAccountService.findByUserId(Id);

        model.addAttribute("name",name);
        model.addAttribute("userInformation",userInformation);

        return "userAccounts/userAccount-info";
    }

    @PostMapping("/uploadFile")
    public String saveImage(Model model,@RequestParam("file") MultipartFile file){
        String fileName = fileService.storeFile(file);

        userInformation.setIconImage(fileName);
        userAccountService.save(userInformation);
        System.out.println(userInformation.toString());
        model.addAttribute("userInformation",userInformation);
        return "userAccounts/userAccount-info";
    }
}
